package com.suxin.http.response;

import com.suxin.http.AbstractRestTemplate;
import com.suxin.http.model.Header;
import com.suxin.http.model.HttpRestResult;
import com.suxin.http.model.Query;
import com.suxin.http.model.RequestHttpEntity;
import com.suxin.http.request.AsyncHttpClientRequest;
import com.suxin.http.request.Callback;
import com.suxin.http.response.handler.ResponseHandler;
import com.suxin.http.response.handler.ResultRestResponseHandler;
import org.springframework.http.HttpMethod;
import org.springframework.web.util.UriComponentsBuilder;

import java.io.IOException;
import java.lang.reflect.Type;
import java.net.URI;
import java.util.concurrent.CompletableFuture;

/**
 * @author Tang
 * @classname AsyncHttpRestTemplate
 * @description [  ]
 * @date 2023/3/5 19:39
 */
public class AsyncHttpRestTemplate extends AbstractRestTemplate {

    final AsyncHttpClientRequest httpClientRequest;

    public AsyncHttpRestTemplate(AsyncHttpClientRequest httpClientRequest) {
        this.httpClientRequest = httpClientRequest;
    }

    /**
     * get
     * @param url
     * @param header
     * @param query
     * @param responseType
     * @param <T>
     * @return
     * @throws Exception
     */
    public <T> void get(String url, Header header, Query query, Type responseType, Callback<T> callback) throws Exception {
        execute(url, HttpMethod.GET.name(), new RequestHttpEntity(header, query), responseType,callback);
    }

    /**
     * post
     * @param url
     * @param header
     * @param query
     * @param body
     * @param responseType
     * @param <T>
     * @return
     * @throws Exception
     */
    public <T> void post(String url, Header header, Query query,Object body, Type responseType, Callback<T> callback) throws Exception {
        execute(url, HttpMethod.POST.name(), new RequestHttpEntity(header, query,body), responseType,callback);
    }

    private <T> void execute(String url, String name, RequestHttpEntity requestHttpEntity, Type responseType, Callback<T> callback) throws Exception {
        // 构建请求的uri
        final URI uri = UriComponentsBuilder
                .fromHttpUrl(url)
                .query(requestHttpEntity.getQuery().toQueryUrl())
                .build()
                .toUri();
        requestHttpClient().execute(uri, name, requestHttpEntity, callback);
    }

    private AsyncHttpClientRequest requestHttpClient() {
        return this.httpClientRequest;
    }

}
